package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    //查询所有
    @Override
    public List<Category> findAll() {
        //调用mapper查询
        List<Category>categoryList=categoryMapper.findAll();
        return categoryList;
    }
    //添加分类
    @Override
    public void save(Category category) {
        //补齐参数
        //id
        category.setId(IdUtil.getSnowflake(1,1).nextId());
        //创建更新时间
        //category.setUpdateTime(new Date());
        //category.setCreateTime(new Date());
        //创建更新人
        //category.setUpdateUser(1L);//临时写死
        //category.setCreateUser(1L);//临时写死
        //调用mapper
        categoryMapper.save(category);
    }
    //更新分类
    @Override
    public void update(Category category) {
        //设置修改更新人和时间
        category.setUpdateTime(new Date());
        category.setCreateTime(new Date());
        //category.setCreateUser(1L);
        //category.setUpdateUser(1L);
        //调用mapper更新
        categoryMapper.update(category);
    }
    //删除分类
    @Override
    public ResultInfo delete(Long id) {
        //1. 查看当前分类下是否有菜品,如果有,不允许删除本分类  查询dish表
        int countDish =categoryMapper.countDishByCategoryId(id);
        if (countDish>0){
            throw new CustomException("当前分类下有菜品,不能删除");
        }
        //2. 查看当前分类下是否有套餐,如果有,不允许删除本分类  查询setmeal表
        int countSetmeal =categoryMapper.countSetmealByCategoryId(id);
        if (countSetmeal>0){
            throw new CustomException("当前分类下有套餐,不能删除");
        }
        //3. 当前分类下什么都没有,可以删除
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }
    //根type查询
    @Override
    public List<Category> findList(Integer type) {
        //调用mapper查询
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        return categoryMapper.selectList(wrapper);
    }
}
